package cn.jbit.service.impl;

import cn.jbit.exception.CustomerException;
import cn.jbit.processlogutil.LogProcessor;
import cn.jbit.service.LogService;
import cn.jbit.util.RespConstant;
import cn.jbit.util.RespPropertiesConfig;
import cn.jbit.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.nio.charset.StandardCharsets;

public abstract class AbstractLogServiceImpl implements LogService {

    Logger logger;

    @Autowired
    RespPropertiesConfig respPropertiesConfig;

    @Autowired
    LogProcessor logProcessor;

    /**
     *
     * @param request  请求的二进制数据
     * @param logType  日志的类型
     * @throws Exception
     */
    @Override
    public void process(HttpServletRequest request, String logType) throws Exception {
        //日志类型为空
        if (StringUtils.isEmpty(logType)){
            throw  new CustomerException(respPropertiesConfig.getMsg(RespConstant.CODE_0001), RespConstant.CODE_0001);
        }

        //获取HTTP报头的content-length
        int contentLength=request.getContentLength();

        if (contentLength<1){
            throw new CustomerException(respPropertiesConfig.getMsg(RespConstant.CODE_0003), RespConstant.CODE_0003);
        }

        //读取数据放到byte数组中
        byte[] bytes=new byte[contentLength];
        BufferedInputStream inputStream=new BufferedInputStream(request.getInputStream());

        //最大读取尝试次数
        int tryTime=0;

        //最大读取尝试次数最终获得的数据长度
        int totalReadLength=0;

        //保证读取输入流里的全部数据，保证尝试读取的数据市场为20s
        int maxTryTime=100;
        //循环读取数据流里的数据
        while (totalReadLength<contentLength&&tryTime<maxTryTime){

            int readLength=inputStream.read(bytes,totalReadLength,contentLength-totalReadLength);

            //读取长度小于0
            if (readLength<0){
                throw  new  CustomerException(respPropertiesConfig.getMsg(RespConstant.CODE_0007), RespConstant.CODE_0007);
            }
            totalReadLength+=readLength;

  /*          if (totalReadLength==contentLength){
                break;
            }*/

            tryTime++;
            //每次尝试读取后延时20s
            Thread.sleep(200);

            inputStream.close();

            //处理数据
            String strings=new String(bytes, StandardCharsets.UTF_8);
            this.log(strings,request,logType);

        }
    }

    @Override
    public void log(String jsonStr, HttpServletRequest request, String logType) throws Exception {

        JSONArray datas=logProcessor.checkJsonArray(jsonStr,logType);
        if (datas.size()>0){

            StringBuilder multiLinesRaw=new StringBuilder();
            for (int index=0,size=datas.size();index<size;index++){
                JSONObject jsonObject=datas.getJSONObject(index);
                multiLinesRaw.append(jsonObject.toString()).append(",");
            }
            String multiLines=multiLinesRaw.toString().substring(0,multiLinesRaw.length()-1);

            try {
                logger.info(multiLines);
            }catch (Exception e){
                throw  new CustomerException(respPropertiesConfig.getMsg(RespConstant.CODE_0006),RespConstant.CODE_0006);
            }
        }

    }
}
